package gov.ccswj.modules.ccbusiness.integratedata;

import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.Key;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.xidea.el.json.JSONDecoder;
import org.xidea.el.json.JSONEncoder;

import com.quantum.auth.RSA2048;

import gov.ccswj.common.utils.AuthUtils;
import gov.ccswj.common.utils.HttpRequest;
import gov.ccswj.modules.app.controller.AuthTest;
import gov.ccswj.modules.ccbusiness.entity.CMainstaffEntity;
import gov.ccswj.modules.ccbusiness.service.CMainstaffService;
import gov.ccswj.modules.ccbusiness.service.impl.CMainstaffServiceImpl;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class test {

	public static void main(String[] args) {
		CMainstaffService cMainstaffService=new CMainstaffServiceImpl();
		String entName="北京东方黑森林贸易有限公司";
		// TODO Auto-generated method stub
		String resultdata = IntegrateDate.getCompanyData("getGeoPositionInfo", "三明市闽中宾馆有限公司",0);
//		List<Object> list=getdate(resultdata,CMainstaffEntity.class);
//		for(Object c:list){
//			CMainstaffEntity cm= new CMainstaffEntity();
//			cm=(CMainstaffEntity)c;
//			cm.setEntname(entName);
//		}
		System.out.println(resultdata);
		
	}
	/**
	 * 返回json 数据转换为 实体类
	 * @param jsonStr  json字符串数据
	 * @param className 要转化的实体类名字
	 * @return
	 */
	public static List<Object> getdate(String jsonStr,Class className) {
		JSONObject json = JSONObject.fromObject(jsonStr);
		JSONArray resultData = (JSONArray) json.get("RESULTDATA");

		List<Object> entityList = new ArrayList<Object>();
		for (Object jsonObject : resultData) {
			JSONObject jsonstr = JSONObject.fromObject(jsonObject);
			jsonstr = transToLowerObject(jsonstr);
		
			Object entity = JSONObject.toBean(jsonstr, className);
			entityList.add(entity);
		}
		return entityList;
	}

	
	/**
	 * * json大写转小写      *       
	 * * @param jSONArray1 jSONArray1    
	 *  * @return JSONObject      
	 */

	public static JSONObject transToLowerObject(JSONObject jSONArray1) {
		JSONObject jSONArray2 = new JSONObject();
		Iterator it = jSONArray1.keys();
		while (it.hasNext()) {
			String key = (String) it.next();
			Object object = jSONArray1.get(key);
			// System.out.println(object.getClass().toString());
			// if (object.getClass().toString().endsWith("String")) {
			// jSONArray2.accumulate(key.toLowerCase(), object);
			// } else if (object.getClass().toString().endsWith("JSONObject")) {
			// jSONArray2.accumulate(key.toLowerCase(),
			// transToLowerObject((JSONObject) object));
			// } else if (object.getClass().toString().endsWith("JSONArray")) {
			// jSONArray2.accumulate(key.toLowerCase(),
			// transToArray(jSONArray1.getJSONArray(key)));
			// }
			jSONArray2.accumulate(key.toLowerCase(), object);
		}
		return jSONArray2;
	}

	/**
	 * jsonArray转jsonArray
	 * 
	 * @param jSONArray1
	 *            jSONArray1
	 * @return JSONArray
	 *//*
		 * public static JSONArray transToArray(JSONArray jSONArray1) {
		 * JSONArray jSONArray2 = new JSONArray(); for (int i = 0; i <
		 * jSONArray1.size(); i++) { Object jArray =
		 * jSONArray1.getJSONObject(i); if
		 * (jArray.getClass().toString().endsWith("JSONObject")) {
		 * jSONArray2.add(transToLowerObject((JSONObject) jArray)); } else if
		 * (jArray.getClass().toString().endsWith("JSONArray")) {
		 * jSONArray2.add(transToArray((JSONArray) jArray)); } } return
		 * jSONArray2; }
		 */
	
	public static String getCompanyData(String methodName, String paramName,Integer pageno) {
		// TODO Auto-generated method stub
		try {
			String uid = "bcc9a8b6f5ea4047b3064da563c47dbd"; // 用户id
			String serviceUrl = "http://121.52.214.35/service";
			String serverName = methodName; // 服务方法名称

			// 服务相关参数的JSON数据
			Map<String, Object> conditoinMap = new HashMap<String, Object>();
			conditoinMap.put("uid", uid);
			conditoinMap.put("service", serverName);

			Map<String, Object> params = new HashMap<String, Object>();
			// params.put("keyword", "用友网络");
			// params.put("type", "0");
			if(pageno == 2){
				params.put("rowKey", paramName);
			}else{
				params.put("keyword", paramName);
				params.put("attIds", "R102;R104;R108");
				params.put("level", "3");
				params.put("nodeType", "GS");
			}
			
			
			conditoinMap.put("params", params);
			String serverParams = JSONEncoder.encode(conditoinMap);

			// 参数加密
			String postParams = MessageFormat.format("uid={0}&data={1}", uid, getPostJsonStr(serverParams, uid));
			// 获取数据 String postParams = MessageF
			// 发送请求
			String result = HttpRequest.sendPost(serviceUrl, postParams);
			result = URLDecoder.decode(result, "UTF-8");
			// 转换数据
			// 参数解密
			Map<String, Object> resultMap = JSONDecoder.decode(result);
			String value = RasAndDesDecode(resultMap, uid);
			System.out.println(value);
			return value;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}
	/**
	 * 服务参数加密
	 *
	 * @param serverParams
	 * @return 返回加密后的密文
	 * @throws Exception
	 */
	private static String getPostJsonStr(String serverParams, String uid) throws Exception {
		Map<String, Object> authParams = AuthUtils.encode(serverParams, getKey(uid));
		return URLEncoder.encode(JSONEncoder.encode(authParams), "UTF-8");
	}

	/**
	 * 解密过程
	 *
	 * @param data
	 * @return
	 * @throws Exception
	 */
	private static String RasAndDesDecode(Map<String, Object> data, String uid) throws Exception {
		return AuthUtils.decode(data, getKey(uid));
	}

	/**
	 * 获取公钥
	 *
	 * @return
	 * @throws Exception
	 */
	private static Key getKey(String uid) throws Exception {
		Key key = null;
		try {
			URL url = AuthTest.class.getResource("/");
			key = RSA2048.getKey(url.getPath() + "public_" + uid + ".key");// 密钥路径
		} catch (Exception ex) {
			throw ex;
		}
		return key;
	}
	
	/**
     * 该方法是用于相同对象不同属性值的合并，如果两个相同对象中同一属性都有值，那么sourceBean中的值会覆盖tagetBean重点的值
     * @param sourceBean    被提取的对象bean
     * @param targetBean    用于合并的对象bean
     * @return targetBean,合并后的对象
     */
    public static Object combineSydwCore(Object sourceBean,Object targetBean){
        Class sourceBeanClass = sourceBean.getClass();
        Class targetBeanClass = targetBean.getClass();
        
        Field[] sourceFields = sourceBeanClass.getDeclaredFields();
        Field[] targetFields = sourceBeanClass.getDeclaredFields();
        for(int i=0; i<sourceFields.length; i++){
            Field sourceField = sourceFields[i]; 
            Field targetField = targetFields[i];  
            sourceField.setAccessible(true);
            targetField.setAccessible(true);
            try {
                if( !(sourceField.get(sourceBean) == null) &&  !"serialVersionUID".equals(sourceField.getName().toString())){
                    targetField.set(targetBean,sourceField.get(sourceBean));
                }
            } catch (IllegalArgumentException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return targetBean;
    }


}
